#ifndef AUTHMANAGER_H
#define AUTHMANAGER_H

#include <QObject>
#include <QVariantMap>
#include "DatabaseManager.h"

class AuthManager : public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool isLoggedIn READ isLoggedIn NOTIFY loginStatusChanged)
    Q_PROPERTY(QString currentUser READ currentUser NOTIFY loginStatusChanged)
    Q_PROPERTY(QString userEmail READ userEmail NOTIFY loginStatusChanged)
    Q_PROPERTY(bool isAdmin READ isAdmin NOTIFY loginStatusChanged)

public:
    explicit AuthManager(QObject *parent = nullptr);
    ~AuthManager();

    // 属性访问器
    bool isLoggedIn() const { return m_isLoggedIn; }
    QString currentUser() const { return m_currentUser; }
    QString userEmail() const { return m_userEmail; }
    int userId() const { return m_userId; }
    bool isAdmin() const { return m_isAdmin; }

    // 公共方法，可被QML调用
    Q_INVOKABLE bool registerUser(const QString &username, const QString &email, const QString &password);
    Q_INVOKABLE bool loginUser(const QString &username, const QString &password);
    Q_INVOKABLE void logoutUser();
    Q_INVOKABLE void clearLoginState();

signals:
    void loginSuccess(const QString &message);
    void loginFailed(const QString &error);
    void registrationSuccess(const QString &message);
    void registrationFailed(const QString &error);
    void logoutSuccess();
    void loginStatusChanged();

private:
    DatabaseManager *dbManager;
    bool m_isLoggedIn;
    QString m_currentUser;
    QString m_userEmail;
    int m_userId;
    bool m_isAdmin;

    // 验证方法
    bool validateEmail(const QString &email);
    bool validatePassword(const QString &password);
    bool validateUsername(const QString &username);
    void setLoginStatus(bool loggedIn, const QString &username = "", const QString &email = "", int userId = -1, bool isAdmin = false);
    
    // 持久化方法
    void saveLoginState();
    void loadLoginState();
};

#endif // AUTHMANAGER_H
